﻿using DotNettyExtensions;
using EasyIot.Repository;
using EasyIot.WebApi.Utility;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using System;

namespace EasyIot.WebApi
{
    public class Startup
    {
        public IWebHostEnvironment Environment { get; }

        public Startup(IConfiguration configuration, IWebHostEnvironment environment)
        {
            Configuration = configuration;
            Environment = environment;
        }

        public IConfiguration Configuration { get; }
         
        public void ConfigureServices(IServiceCollection services)
        {
            var appSettings = (ConfigurationSection)Configuration.GetSection("AppSettings");

            // mysql 初始化 
            DbContext.ConnectionString = appSettings["ConnectionString"].ToString(); 

            // tcpserver 初始化 
            int serverPort = Convert.ToInt32(appSettings["ServerPort"]);
            new ServerIntance(serverPort, new ClientProtocol(), true);
            ServerMgr.StartTask();

            services.AddControllersWithViews(); 

            //添加Swagger.
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo { Title = "Protected API", Version = "v1" }); 
            });

            //配置跨域
            services.AddCors(options =>
            {
                options.AddPolicy("LimitRequests", policy =>
                {
                    // 支持多个域名端口，注意端口号后不要带/斜杆
                    // 注意，http://127.0.0.1:1818 和 http://localhost:1818 是不一样的，尽量写两个
                    policy

                         // 不支持向所有域名开放， AllowAnyOrigin 不可用
                         //.WithOrigins(AppSettings.app(new string[] { "Startup", "Cors", "IPs" }).Split(','))
                         .SetIsOriginAllowed(x => true)
                        .AllowAnyHeader()//允许任何头
                        .AllowAnyMethod()//允许任何方式
                        .AllowCredentials();//允许cookie
                });
            });
            services.AddControllers(config =>
            {
                config.Filters.Add(new CorsActionFilter());
            });

            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
        }
         
        public void Configure(IApplicationBuilder app)
        {
            if (Environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            // Swagger JSON Doc
            app.UseSwagger();

            // Swagger UI
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger API V1");
                options.OAuthClientId("api_swagger");//客服端名称
                options.OAuthAppName("Swagger API"); // 描述
            });
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            }); 
        } 
    }
}
